<template>
  <div class="register-page">
    <div class="register-container">
      <h2>注册</h2>

      <el-radio-group v-model="isDoctor" size="medium" class="identity-switch">
        <el-radio-button :label="false">患者注册</el-radio-button>
        <el-radio-button :label="true">医生注册</el-radio-button>
      </el-radio-group>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号">
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="职称" v-if="isDoctor" prop="level">
          <el-input v-model="form.level" placeholder="例如 主治医师">
            <template #prefix>
              <el-icon><Star /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="医院ID" v-if="isDoctor" prop="hospitalId">
          <el-input v-model.number="form.hospitalId" placeholder="请输入医院ID">
            <template #prefix>
              <el-icon><OfficeBuilding /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleRegister" class="register-button">注册</el-button>
        </el-form-item>
      </el-form>

      <p class="login-link">
        已有账号？<router-link to="/login">点击登录</router-link>
      </p>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api' // 假设 api 路径是正确的
import { User, Iphone, Lock, Star, OfficeBuilding } from '@element-plus/icons-vue' // 导入 Element Plus 图标

export default {
  name: 'MyRegister',
  components: {
    User,
    Iphone,
    Lock,
    Star,
    OfficeBuilding,
  },
  setup() {
    const isDoctor = ref(false)
    const formRef = ref(null)
    const form = ref({
      name: '',
      phone: '',
      password: '',
      level: '',
      hospitalId: null,
    })

    const rules = computed(() => ({
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
      ],
      level: isDoctor.value
          ? [{ required: true, message: '请输入职称', trigger: 'blur' }]
          : [],
      hospitalId: isDoctor.value
          ? [{ required: true, message: '请输入医院ID', trigger: 'blur' },
            { type: 'number', message: '医院ID必须是数字', trigger: 'blur' }]
          : [],
    }))

    const handleRegister = async () => {
      // 检查 formRef.value 是否存在，因为在 mounted 之前可能为 null
      if (!formRef.value) {
        ElMessage.error('表单组件未加载完成，请稍后重试。');
        return;
      }

      const valid = await formRef.value.validate().catch(() => false);
      if (!valid) return;

      let url = ''
      let params = {}

      if (isDoctor.value) {
        url = '/doctor/register'
        params = {
          name: form.value.name,
          phone: form.value.phone,
          password: form.value.password,
          level: form.value.level,
          hospitalId: form.value.hospitalId,
        }
      } else {
        url = '/user/register'
        params = {
          name: form.value.name,
          phone: form.value.phone,
          password: form.value.password,
        }
      }

      try {
        const res = await api.post(url, params)
        if (res.status === 200 && res.data.code === 200) {
          ElMessage.success('注册成功！即将跳转到登录页。')
          // 清空表单或跳转登录页
          // 注意：在 setup 中访问 router 需要通过 useRoute 或 useRouter
          // 如果你的项目使用 Vue Router 4，需要像这样：
          // import { useRouter } from 'vue-router';
          // const router = useRouter();
          // router.push('/login');
          // 假设你已经在 main.js 或其他地方正确配置了 router，这里直接跳转
          setTimeout(() => { // 延迟跳转，给用户看到提示的时间
            window.location.href = '/login'; // 直接改变location实现跳转，或者用 router.push
          }, 1500);

        } else {
          ElMessage.error('注册失败：' + (res.data.msg || '未知错误'))
        }
      } catch (error) {
        console.error('注册请求失败:', error);
        ElMessage.error('请求失败，请检查网络或接口服务。');
      }
    }

    return {
      isDoctor,
      form,
      formRef,
      rules,
      handleRegister,
    }
  },
}
</script>

<style scoped>
/* 全屏背景 */
.register-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  /* 使用与登录页相似的渐变背景，保持视觉一致性 */
  background: linear-gradient(to top left, #add8e6, #87ceeb);
  animation: background-animate 15s ease infinite;
}

@keyframes background-animate {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* 注册容器 */
.register-container {
  width: 420px; /* 注册表单通常更长，稍微增加宽度 */
  padding: 45px 50px; /* 增大内边距 */
  background-color: rgba(255, 255, 255, 0.96); /* 稍微更实心的白色背景 */
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.18); /* 更明显的阴影 */
  animation: slide-in 0.8s ease-out forwards;
}

@keyframes slide-in {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 30px; /* 标题字号更大 */
  color: #333;
  font-weight: 700; /* 标题字重更粗 */
}

/* 身份切换按钮组 */
.identity-switch {
  margin-bottom: 30px; /* 增大与表单的间距 */
  display: flex;
  justify-content: center;
}

/* 确保 el-radio-button 在这里也有美化 */
.identity-switch .el-radio-button {
  border-radius: 6px;
  overflow: hidden; /* 防止内边框溢出圆角 */
}

.identity-switch .el-radio-button__inner {
  border: 1px solid #dcdfe6;
  padding: 10px 20px; /* 按钮内边距 */
  font-size: 16px; /* 按钮文字大小 */
  color: #606266;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
}

.identity-switch .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
  box-shadow: -1px 0 0 0 #409EFF;
}

.identity-switch .el-radio-button__inner:hover {
  color: #409EFF;
}

/* Element Plus 表单项和输入框样式调整 */
.el-form-item {
  margin-bottom: 25px; /* 调整表单项间距 */
}

.el-input {
  border-radius: 6px; /* 输入框圆角 */
}

/* 按钮样式 */
.register-button {
  width: 100%;
  border-radius: 8px; /* 按钮圆角 */
  height: 48px; /* 按钮高度 */
  font-size: 18px; /* 按钮文字大小 */
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.35); /* 按钮阴影 */
  transition: all 0.3s ease;
  margin-top: 10px; /* 稍微增加与上一个表单项的间距 */
}

.register-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.45);
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-top: 25px; /* 增大与按钮的间距 */
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.login-link a:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>